$(function(){
	// Zebra table:
	$("table.zebra tr:even td").css({background: "#eee"});
	$("table.zebra tr:odd td").css({background: "#f9f9f9"});
	
	// Edit / Delete buttons enabled / disable:
	$("input[name=edit], input[name=delete]").attr("disabled", "disabled");
	$(".optionlist input[type=radio]").click(function(){
		$("input[name=edit], input[name=delete]").removeAttr("disabled");
	});

	// Confirmation on delete:
	$("input[name=delete]").click(function(){
		return confirm('Are you sure you wish to delete this item? This action cannot be undone!');
	});
	
	// Option: CategorySelector:	
	$("select[name=type]").change(function(){
		if($(this).val()=='category') {
			$(".categorySelector").show();
			$(".defaultValue").hide();
		} else {
			$(".categorySelector").hide();
			$(".defaultValue").show();
		}
	});
	$("select[name=type]").change();
	
	// Link to add another option to the datatypes:
	var nr = parseInt($("var#nr").text());
	$("a.add").click(function(){
		$("select[name=option_"+nr+"]"); // .after(' - <a href="#" class="delete">delete</a>');
		nr++;	
		$.get('core/ajax.datatypes_option.php', {nr: nr}, function(data){
			$("div.options ol").append(data);
			linkDeleteOption();
		});
		return false;
	});
	linkDeleteOption();
	
	// Link to add another value to the item:
	$("a.addAnother").click(function(){
		var parent      = $(this).parent().parent();	
		var type        = $("var.type", this).text();
		var optionID    = $("var.optionID", this).text();
		var manycounter = $("input[name=manycounter]").val();
		manycounter++;
		$("input[name=manycounter]").val(manycounter);
		$.get('core/ajax.item_hasmany.php', {type: type, optionID: optionID, manycounter:manycounter}, function(data){
			parent.append(data);
		});
		return false;
	});
	
	// Load the expand buttons:
	setExpandButtons();
});

function linkDeleteOption() {
	$("a.delete").click(function(){
		$(this).parent().remove();
	});
}

function setExpandButtons() {	
	$("span.expand").unbind("click");
	// $("td.expandable").unbind("click");
	$("span.expand").click(function(){				
		var id     = $("var.id", this).text();
		var target = "loader_"+id;
		if($(".arrow", this).text()=='+') {			
			$(this).parent().append('<div id="'+target+'"></div>');
			$("#"+target).load("core/ajax.load_item.php", {id: id}, function(){				
				setExpandButtons();
			});
			$(".arrow", this).text('-');
		} else {
			$("#"+target).remove();
			$(".arrow", this).text('+');			
		}
	});	
	/*
	$("td.expandable").click(function(){
		$("span.expand", this).click();
	});
	*/
}